package com.fyzk.activity.forum;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RadioButton;

import com.alibaba.fastjson.JSON;
import com.fyzk.base.BaseActivity;
import com.fyzk.activity.user.NetProgressView;
import com.fyzk.data.preference.MySharedPreferences;
import com.tyjc.lottery.R;
import com.fyzk.net.Commands;
import com.fyzk.utils.LogUtil;
import com.fyzk.view.RefreshListView;
import com.fyzk.view.TopTitleView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.http.body.RequestBody;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import http.Common.CommandUtil;
import com.wf.domain.UrlDef;
import http.StringResultBean;

/**
 * Created by fanxs11 on 17/5/5.
 * 我的帖子
 */
@ContentView(R.layout.ac_forum_mypost)
public class ForumMyPostActivity extends BaseActivity implements RefreshListView.OnRefreshListener {

    @ViewInject(R.id.forum_mypost_topview)
    private TopTitleView topView;

    @ViewInject(R.id.mypost_rb_post)
    private RadioButton myPost_rb;      // 我的帖子

    @ViewInject(R.id.mypost_rb_reply)
    private RadioButton myReply_rb;     // 我的回复

    @ViewInject(R.id.mypost_listview)
    private RefreshListView listView;
    private MyPostAdapter adapter;

    @ViewInject(R.id.mypost_recordProgressView)
    private NetProgressView recordProgressView;

    public static List<TopicListBean> infos = new ArrayList<>();

    private static final int STATUS_POST = 1;     // 我的帖子
    private static final int STATUS_REPLY = 2;    // 我的回复

    private int status = STATUS_POST;

    private boolean requestType = false;    //请求方式：true加载更多，false首次请求或刷新
    private int page = 1;
    private int count = 10;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initView();
        net();
    }

    private void initView() {
        topView.setOnTitleClickListener(this);

        myPost_rb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                if (b) {
                    page = 1;
                    status = STATUS_POST;
                    infos.clear();
                    net();
                }

            }
        });

        myReply_rb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                if (b) {
                    page = 1;
                    status = STATUS_REPLY;
                    infos.clear();
                    net();
                }

            }
        });

        listView.setItemsCanFocus(false);
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        listView.setOnRefreshListener(this);
        adapter = new MyPostAdapter(this);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (listView.isDownPull){
                    return;
                }
                if (i > 0 && i <= infos.size()) {
                    Intent intent = new Intent(getContext(), TopicDetailActivity.class);
                    intent.putExtra("id", infos.get(i - 1).getQuestion_id());
                    startActivity(intent);
                }


            }
        });
    }

    /**
     * 获取我的帖子
     */
    private void getMyPost() {
        try {
            JSONObject request_json = new JSONObject();
            request_json.put("token", MySharedPreferences.getInstance().getAuthtoken());
            request_json.put("time", System.currentTimeMillis());
            JSONObject data = new JSONObject();
            data.put("post_type", "question");
            data.put("page", page);
            data.put("per_page", count);
            data.put("sort_type", "");
            request_json.put("data", data);
            LogUtil.d("联网请求json:"+request_json.toString());
            RequestParams params = new RequestParams(UrlDef.FORUM_URL + Commands.FORUM_MYPOST);

            params.setBodyContent("req="+ URLEncoder.encode(request_json.toString(), "UTF-8"));
            RequestBody body = params.getRequestBody();
            body.setContentType("application/x-www-form-urlencoded");
            params.setRequestBody(body);

            sendRequest(HttpMethod.POST, CommandUtil.FORUM_MYPOST, params, true);
        } catch (JSONException e) {

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        recordProgressView.dismiss();
        List<TopicListBean> beans = JSON.parseArray(resultBean.getData(), TopicListBean.class);
        LogUtil.d("size: "+beans.size());
        if (requestType) {  // 加载更多
            if (beans.size() > 0) {
                infos.addAll(beans);
                listView.hideFooterView();
            } else {
                listView.noMore();
            }
        } else {
            infos = beans;
            listView.hideHeaderView();
            if (infos.size() == 0) {
                listView.noMore();
            }
        }
        adapter.notifyDataSetChanged();
        requestType = false;
    }

    @Override
    protected void onFailure(int requestCode, String errorcode,String message) {
        if(errorcode.equals("900003")){ // 数据为空
            if (!requestType) { // 下拉刷新或第一次请求
                infos.clear();
                recordProgressView.noneRecord(message);

            } else {    // 加载更多
                listView.noMore();

            }
        }
        adapter.notifyDataSetChanged();
    }

    private void net(){
//        DJ_ProgressDialog.show(getContext(), true, true);
        getMyPost();
    }

    @Override
    public void onDownPullRefresh() {
        page = 1;
        requestType = false;
        net();
    }

    @Override
    public void onLoadingMore() {
        requestType = true;
        page++;
        net();
    }
}
